<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="formRef" :inline="true" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <!--          <el-col :span="6">-->
          <!--            <el-form-item label="住院号" prop="hospitalNo">-->
          <!--              <el-input v-model="form.hospitalNo" :disabled="true"/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="7">
            <el-form-item label="患者信息" prop="name">
              <span v-if="!form.name">暂无患者</span>
              <span v-else>
                                <span class="fz15 mr5" style="color: #7171ff">{{
                                    form.name
                                  }}</span>
                                <span class="fz13 mr5">{{ form.age }} 岁{{ form.ageMonth }} 月{{
                                    form.ageDay
                                  }}天{{
                                    form.ageHours
                                  }}小时</span>

                                <svg-icon :icon-class="dictStore.getMateDictInfo(dictDataMap['sys_user_sex'], form.sex)
                                    .dictValue === '1'
                                    ? 'man'
                                    : 'woman'
                                    "/>
                            </span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号" prop="idNo">
              <el-input v-model="form.idNo" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入院病区" prop="wardAdmissionToName">
              <el-input v-model="form.wardAdmissionToName" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="发病时间" prop="situationTime">
              <el-input v-model="form.situationTime" :disabled="true"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="入院情况" prop="hospitalSituation">
              <dict-data-tag :options="dictDataMap['admission_situation_dict']"
                             :value="form.hospitalSituation"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider/>
        <el-row>
<!--          <el-col :span="6">-->
<!--            <el-form-item label="护理等级" prop="nursingClass">-->
<!--              <el-select v-model="form.nursingClass" class="nurse-class"-->
<!--                         placeholder="请选择护理等级" style="width: 120px" @change="nurseClassChange($event, '1')">-->
<!--                <el-option v-for="nurseClass in nurseClassList" :key="nurseClass.dictValue"-->
<!--                           :label="nurseClass.dictLabel" :value="nurseClass.dictValue">-->
<!--                  <div>-->
<!--                    <el-tag :type="nurseClass.listClass">-->
<!--                      {{ nurseClass.dictLabel }}-->
<!--                    </el-tag>-->
<!--                  </div>-->
<!--                </el-option>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="7">
            <el-form-item label="责任护士" prop="dutyNurse">
              <el-select v-model="form.dutyNurse" placeholder="请选择"
                         style="width: 120px">
                <el-option v-for="item in orgVsUserList" :key="item.userId" :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="质控护士" prop="qualityNurse">
              <el-select v-model="form.qualityNurse" placeholder="请选择"
                         style="width: 120px">
                <el-option v-for="item in orgVsUserList" :key="item.userId" :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
              <el-form-item label="上级医生" prop="upperDoctor">
                  <el-select :disabled="!form.visitId" v-model="form.upperDoctor" placeholder="请选择"
                      style="width: 120px">
                      <el-option v-for="item in orgVsUserList" :key="item.userId" :label="item.nickName"
                          :value="item.userId" />
                  </el-select>
              </el-form-item>
          </el-col> -->
          <!-- <el-col :span="6">
              <el-form-item label="主任医生" prop="directorDoctor">
                  <el-select :disabled="!form.visitId" v-model="form.directorDoctor" placeholder="请选择"
                      style="width: 120px">
                      <el-option v-for="item in orgVsUserList" :key="item.userId" :label="item.nickName"
                          :value="item.userId" />
                  </el-select>
              </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-button class="mb5 mr5" style="float: right;" type="primary"
                       @click="submitForm">移入病区确认
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row>待入病区患者列表</el-row>
    <el-form ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
      <el-form-item label="入院登记时间" prop="admissionTime">
        <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期" range-separator="截止"
                        start-placeholder="开始日期" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                        @change="handleQuery"></el-date-picker>
      </el-form-item>
      <el-form-item label="患者名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入患者名称" @keyup.enter="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <template #icon>
            <i-ep-search/>
          </template>
          搜索
        </el-button>
      </el-form-item>
    </el-form>
    <el-table v-adaptive="600" :border="true" :data="patVisitList" :header-cell-style="$headerCellStyle" :stripe="true"
              highlight-current-row @row-click="patVisitTableClick">
      <!--      <el-table-column :align="'center'" label="住院号" prop="hospitalNo" width="150px"/>-->
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="患者姓名" min-width="140px" prop="name"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="性别" prop="sex" width="90">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_user_sex']" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="年龄" prop="age" width="220px">
        <template #default="scope">
          {{ scope.row.age }} 岁
          {{ scope.row.ageMonth }} 月
          {{ scope.row.ageDay }} 天
          {{ scope.row.ageHours }} 时
          {{ scope.row.ageMinutes }} 分
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="身份证号" prop="idNo" width="200px"/>
      <el-table-column :align="'center'" label="电话" prop="phone" width="150px"/>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" label="费别" prop="chargeType" width="160px">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['medical_insurance_type']" :value="scope.row.chargeType"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="申请入院科室" prop="deptAdmissionToName" width="150px"/>

      <el-table-column :align="'center'" label="住院次数" prop="hospitalizationNumber" width="97"/>
    </el-table>
    <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total"
                @pagination="getList"/>
  </div>
</template>
<script lang="ts" setup>
import {selectPagePatVisit, updatePatVisit} from "@/api/hospitalization/patVisit.ts";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {getOrgVsUserList} from '@/api/system/user';
import {listSysOrgDict} from "@/api/system/sysOrgDict";

const emits = defineEmits(["transferToTheWardOk"])
const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('discharge_disposition_dict', 'patient_class_dict', 'sys_yes_no', 'admission_situation_dict',
  'entry_and_exit_hospital_status', 'medical_insurance_type', 'sys_user_sex'
))
// 护理字典集合
const nurseClassList = ref<any>([])
// 选中可是下用户list
const orgVsUserList = ref<any>([])
const form = ref<any>({})
// 床位信息
const bedInfo = ref<any>({})
const formRef = ref()
const patVisitList = ref<any>([])
const total = ref(0);
const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: userInfo.orgId,
  hospitalNo: "",
  wardFlag: "N",
  inFlag: "1"
  // inFlagArray: ["4"]
})

// 表单校验
const rules = ref({
  nursingClass: [
    {required: true, message: "护理等级不能为空", trigger: "change"}
  ],
  dutyNurse: [
    {required: true, message: "责任护士不能为空", trigger: "change"}
  ],
  qualityNurse: [
    {required: true, message: "质控护士不能为空", trigger: "change"}
  ]
})

function openTransferToTheWard(item) {
  bedInfo.value = {}
  bedInfo.value = item
  empty()
  getList()
}

function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (valid) {
      ElMessageBox.confirm("确定要将此患者移入病区吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let formData = form.value
        formData.bedId = bedInfo.value.bedId
        formData.isTransferToTheWard = '1'
        updatePatVisit(formData).then(() => {
          ElMessage.success("患者移入病区成功")

          emits("transferToTheWardOk")
        })
      }).catch(() => {

      });
    }
  });
}

function empty() {
  patVisitList.value = []
  form.value = {}
  dateRange.value = [date + "00:00:00", date + "23:59:59"]
}

function handleQuery() {
  getList()
}

/** 查询患者住院信息列表 */
function getList() {
  selectPagePatVisit(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    patVisitList.value = response.rows;
    total.value = response.total;
  });
}


function patVisitTableClick(row: any) {
  getOrgVsUserList({deptId: currentSelectDept}).then((res: resType) => {
    orgVsUserList.value = res.data
    form.value = row
  })
}

/** 查询机构字典（护理等级） */
function listSysOrgDictFun() {
  listSysOrgDict({orgId: userInfo.orgId, dictType: "nurse_class"}).then((res: resType) => {
    nurseClassList.value = res.data
  })
}

function nurseClassChange(event, type) {
  let style = {
    backColor: "fef0f0",
    color: "ff0000"
  }
  // 获取选中的数据与元数据匹配项
  const nurseClassIndex = nurseClassList.value.findIndex(obj => {
    return obj.value == event
  })
  if (nurseClassIndex > -1) {
    const nurseClassInfo = nurseClassList.value[nurseClassIndex]
    style = proxy.$mateStyle(nurseClassInfo);
    const nurseClassRef = "nurse-class";
    const elements = document.getElementsByClassName(nurseClassRef);
    // 遍历所有获取到的元素
    // for (var i = 0; i < elements.length; i++) {
    //   // 对元素设置背景色
    //   elements[i].children[0].style.backgroundColor = style.backColor;
    //   // 对元素设置字体颜色
    //   if (type === '1') {
    //     elements[i].children[0].children[0].children[1].children[0].style.color = style.color;
    //   } else {
    //     elements[i].children[0].children[0].children[1].children[0].style.color = style.color;
    //   }
    //
    // }
  }
}

onUpdated(() => {
  nurseClassChange(form.value.nursingClass, "2")
})
listSysOrgDictFun()
defineExpose({
  openTransferToTheWard,
  empty
})
</script>

<style lang="scss" scoped>
:deep(.el-divider--horizontal) {
  margin: 10px 0;
}
</style>
